<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import useSaveReminderService from './service'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: () => false,
    },
    orderIds: {
      type: Array<string>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'update'): void
  }>()

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService(['remindEmpType'])

  const visible = ref(false)

  // 使用服务
  const { form, saveReminderLoading, saveReminderFn } = useSaveReminderService(props.orderIds)

  // 提醒人员类型下拉选项：1-工单客服，2-服务商负责人，3-工程师
  const remindEmpTypeOptional = ref([
    { label: '工单客服', value: 1 },
    { label: '服务商负责人', value: 2 },
    { label: '工程师', value: 3 },
  ])

  // 验证规则
  const rules = ref<FormRules<typeof form>>({
    content: [
      {
        required: true,
        message: '请输入催单内容',
        trigger: ['change', 'blur'],
      },
    ],
    remindEmpType: [
      {
        required: true,
        message: '请选择提醒人员',
        trigger: ['change', 'blur'],
      },
      {
        validator: (rule, value: Array<number>, callback) => {
          if (form.value.remindEmpType.length <= 0) {
            callback(new Error('请选择提醒人员'))
          } else {
            callback()
          }
        },
        trigger: ['change', 'blur'],
      },
    ],
  })

  /**
   * 取消事件
   */
  const onCancel = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    visible.value = false
    resetFormValidateResult()
    emits('update:modelValue', visible.value)
  }

  // 表单组件实例
  const formRef = ref<FormInstance | null>(null)

  // 保存事件
  const onSave = () => {
    if (formRef.value) {
      formRef.value.validate(async (valid) => {
        if (valid) {
          const res = await saveReminderFn()
          ElMessage({
            type: res.success ? 'success' : 'error',
            message: res.message,
          })
          if (res.success) {
            onCancel()
            emits('update')
          }
        }
      })
    }
  }

  watch(
    props,
    (value) => {
      form.value.workIds = value.orderIds
      visible.value = value.modelValue
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <div>
    <HModal @close="onCancel" v-model="visible" title="催单" width="auto">
      <el-form
        ref="formRef"
        :rules="rules"
        :model="form"
        @validate="handleFormValidate"
        class="modal_form_content"
      >
        <!--提醒人员-->
        <el-form-item
          label="提醒人员"
          prop="remindEmpType"
          class="form_select_item"
          :class="{ error_form_item: !formValidateResult['remindEmpType'] }"
        >
          <el-select
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            placeholder="请选择"
            v-model="form.remindEmpType"
            class="factory_product"
          >
            <el-option
              v-for="item in remindEmpTypeOptional"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!--催单备注-->
        <el-form-item required label="催单备注" prop="content" class="form_textarea_item">
          <el-input
            v-model="form.content"
            type="textarea"
            placeholder="请输入催单备注"
            resize="both"
          />
        </el-form-item>
      </el-form>

      <template #footerRight>
        <HButton is-modal type="primary" :disabled="saveReminderLoading" @click="onSave">
          保存
        </HButton>
        <HButton isModal :disabled="saveReminderLoading" @click="onCancel">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './Reminder.scss';
</style>
